import { useHistory, useLocation } from 'react-router-dom';
import { useEffect } from 'react';
import Debug from 'debug';
import invariant from 'tiny-invariant';

const debug = Debug(module.id);

export function useInterception() {
  const history = useHistory();
  const location = useLocation();
  useEffect(() => {
    invariant(history.location === location, () => 'useHistory().location should equal to useLocation()');
    debug('Interception useHistory useLocation', history.location.pathname, location.pathname, history.location === location);
    const tip = 'Are you sure you want to leave this page?' + history.location.pathname;
    // return history.block(tip);
    return history.block((location, action) => {
      // 这里的 location 是将要到达的路由，action 也为到达新路由用到的方式，而 history.location 是当前所处的路由
      debug(`in history.block`, history.location, location, history.location === location, action);
      invariant(history.location !== location, () => 'useHistory().location should not equal to history.block(location =>)');
      return tip;
    });
  }, []);
}

export default function Interception() {
  useInterception();
  return null;
}
